<template>
   <div class="container">
    <div id="container">
  </div>
  <div class="bg"></div>
  </div>
</template>

<script lang="ts">
import { defineComponent, PropType, onMounted, ref, watch, reactive } from 'vue';
import Konva from 'konva';
import { computed } from 'vue';
declare global {
  interface Window {
    getEnv: (name: string) => any;
    confirmEdit: () => void;
    cancelEdit: () => void;
  }
}


interface IItem {
  name:string,
  x: number; 
  y: number;
  width: number; 
  height: number; 
  draggable:boolean,
  url:string
}
interface IPiece {
  shapes:Array<IItem>
  
}

const ENUM_ELEM_TYPE = {
  KING_WHITE: 0, // 白王棋
  KING_BLACK: 1, // 黑王棋
  PAWN_WHITE: 2, // 白兵棋
  PAWN_BLACK: 3, // 黑兵棋
  PASSPOINT: 4, // 途经点
  TERMINAL: 5, // 终点
};

export default defineComponent({
  props: {
    basicPropsValue: {
      type: Object as PropType<{ width: number, height: number }>,
      default: () => ({ width: 1100, height: 600 })
    },
    preset: { type: Array as PropType<IPiece[]>, default: () => [] },
    onValueUpdated: { type: Function as PropType<(v: IPiece[]) => void> }
  },
  setup(props) {
    const editingPreset = ref({} as IPiece);
    const refCanvas = ref(null as null | HTMLDivElement);
    let stage = reactive({} as any)
    let layer = reactive({} as Konva.Layer)
    let gridLayer = reactive({} as Konva.Layer)
    let shadowRectangle = reactive({} as any)
    let tr = reactive({} as Konva.Transformer)
    console.log(props.basicPropsValue);
    const width = computed(() => props.basicPropsValue.width)
    const height = computed(() => props.basicPropsValue.height)
    const blockSnapSize = 100;
    onMounted(() => {
      if (props.preset) {
        editingPreset.value = JSON.parse(JSON.stringify(props.preset));
      }
      inKonva()
      console.log(stage);

    });
    function inKonva() {
      stage = new Konva.Stage({
        container: 'container',
        width: width.value,
        height: height.value,
      });
      layer = new Konva.Layer();
      gridLayer = new Konva.Layer();
      shadowRectangle = new Konva.Rect({
        x: 0,
        y: 0,
        width: blockSnapSize,
        height: blockSnapSize,
        fill: '#FF7B17',
        opacity: 0,
        stroke: '#CF6412',
        strokeWidth: 3,
        dash: [20, 2]
      });
      layer.add(shadowRectangle);
      tr = createTransformer();
      createLine()
      stage.add(gridLayer);
      stage.add(layer);
      renderShapes()
    }
    function createLine() {
      var padding = blockSnapSize;
      for (var i = 0; i < width.value / padding; i++) {
        gridLayer.add(new Konva.Line({
          points: [Math.round(i * padding) + 0.5, 0, Math.round(i * padding) + 0.5, height.value],
          stroke: '#ddd',
          opacity: 0,
          strokeWidth: 1,
        }));
      }
      gridLayer.add(new Konva.Line({ points: [0, 0, 10, 10] }));
      for (var j = 0; j < height.value / padding; j++) {
        gridLayer.add(new Konva.Line({
          points: [0, Math.round(j * padding), width.value, Math.round(j * padding)],
          stroke: '#ddd',
          opacity: 0,
          strokeWidth: 0.5,
        }));
      }
      shadowRectangle.hide();
    }
    function createTransformer() {
      return new Konva.Transformer({
        rotateEnabled: true,
        resizeEnabled: false,
        rotateAnchorOffset: 30, // 旋转控制柄与图形的距离
        anchorSize: 40, // 旋转控制柄的大小
        borderStrokeWidth: 2, // 边框粗细
        rotationSnaps: [-180, -0, 0, 180],
      });
    }
    function renderShapes(){
      console.log( " editingPreset.value",editingPreset.value);
      editingPreset.value.shapes.forEach(item=>{
        const {name,x,y,width,height,draggable,url} = item
        createImage(name,x,y,width,height,draggable ,getImageUrlFromPath(url))
      })
        // createBackground(getImageUrlFromPath("controls/checkers/resources/images/bg.jpg"))
        // createImage(100, 200, getImageUrlFromPath("controls/checkers/resources/images/zf.png"))
        // createImage(100, 200, getImageUrlFromPath("controls/checkers/resources/images/zy.png"))
        // createImage(100, 200, getImageUrlFromPath("controls/checkers/resources/images/mc.png"))
        // createImage(100, 200, getImageUrlFromPath("controls/checkers/resources/images/hz.png"))
        // createImage(200, 100, getImageUrlFromPath("controls/checkers/resources/images/gy.png"))
        // createImage(200, 200, getImageUrlFromPath("controls/checkers/resources/images/cc.png"))
        // createImage(100, 100, getImageUrlFromPath("controls/checkers/resources/images/zu.png"))
        // createImage(100, 100, getImageUrlFromPath("controls/checkers/resources/images/zu.png"))
        // createImage(100, 100, getImageUrlFromPath("controls/checkers/resources/images/zu.png"))
        // createImage(100, 100, getImageUrlFromPath("controls/checkers/resources/images/zu.png"))
    }
    function createImage(name,x,y,width,height,draggable,url) {
            var imageObj = new Image();
            imageObj.onload = function () {
                var yoda = new Konva.Image({
                    x: x,
                    y: y,
                    name:name,
                    image: imageObj,
                    width: width,
                    height: height,
                    draggable: draggable
                });

                yoda.on('dragstart', (e) => {
                    shadowRectangle.show();
                    shadowRectangle.moveToTop();
                    yoda.moveToTop();
                });
                yoda.on('dragend', (e) => {
                    yoda.position({
                        x: Math.round(yoda.x() / blockSnapSize) * blockSnapSize,
                        y: Math.round(yoda.y() / blockSnapSize) * blockSnapSize
                    });
                    console.log(e.target.attrs);
                    const {x,y,name}=e.target.attrs
                    editingPreset.value.shapes.forEach(item=>{
                   if(item.name ==name) {
                    item.x =x,
                    item.y =y
                   }
                  })
                    stage.batchDraw();
                    shadowRectangle.hide();
                });
                yoda.on('dragmove', (e) => {
                    shadowRectangle.position({
                        x: Math.round(yoda.x() / blockSnapSize) * blockSnapSize,
                        y: Math.round(yoda.y() / blockSnapSize) * blockSnapSize
                    });
                    stage.batchDraw();
                });
                layer.add(yoda);
                stage.batchDraw();
            };
            imageObj.src = url;
        }

    watch(editingPreset, () => {
      console.log(editingPreset);
      
      if (props.onValueUpdated) {
        props.onValueUpdated(JSON.parse(JSON.stringify(editingPreset.value)));
      }
    }, { deep: true });

    function getImageUrlFromPath(imagePath: string) {
      const fullPath = (window.getEnv('fullPath') || '').trim().replace(/\/*$/, '');
      return `${fullPath}/${imagePath}`;
    }

    // function onClickBoard(evt: MouseEvent) {
    //   if (refBoard.value) {
    //     const boardRect = refBoard.value.getBoundingClientRect();
    //     const cellWidth = boardRect.width / 10;
    //     const cellHeight = boardRect.height / 10;
    //     const { clientX, clientY } = evt;
    //     const x = Math.floor((clientX - boardRect.left) / cellWidth);
    //     const y = Math.floor((clientY - boardRect.top) / cellHeight);
    //     const piece = findPiece(editingPreset.value, { x, y });
    //     if (!piece) {
    //       editingPreset.value.push({ c: 0, x, y, fixed: false });
    //     } else if ([0, 1, 2, 3, 4].indexOf(piece.c) !== -1) {
    //       piece.c += 1;
    //     } else {
    //       editingPreset.value.splice(editingPreset.value.indexOf(piece), 1);
    //     }
    //   }
    // }

    // function getPieceBackgroundImageUrl(type) {
    //   if (type === ENUM_ELEM_TYPE.KING_BLACK) {
    //     return getImageUrlFromPath('controls/checkers/resources/image/piece2.png');
    //   } else if (type === ENUM_ELEM_TYPE.KING_WHITE) {
    //     return getImageUrlFromPath('controls/checkers/resources/image/piece1.png');
    //   } else if (type === ENUM_ELEM_TYPE.PAWN_BLACK) {
    //     return getImageUrlFromPath('controls/checkers/resources/image/pawn_black.png');
    //   } else if (type === ENUM_ELEM_TYPE.PAWN_WHITE) {
    //     return getImageUrlFromPath('controls/checkers/resources/image/pawn_white.png');
    //   } else if (type === ENUM_ELEM_TYPE.PASSPOINT) {
    //     return getImageUrlFromPath('controls/checkers/resources/image/passpoint.png');
    //   } else if (type === ENUM_ELEM_TYPE.TERMINAL) {
    //     return getImageUrlFromPath('controls/checkers/resources/image/terminal.png');
    //   }
    //   return '';
    // }

    return {
      editingPreset,
      refCanvas,
      // boardBgImageUrl: getImageUrlFromPath('controls/checkers/resources/image/board-bg.png'),
      // refBoard,
      // onClickBoard,
      // getPieceBackgroundImageUrl,
    };
  }
})
</script>

<style lang="less" scoped>
.container {
  position: relative;
  box-sizing: border-box;
  user-select: none;
  width: 100%;
  height: 100%;
  .bg {
    position: absolute;
    width: 440px;
    height: 544px;
    top: 80px;
    left: 80px;
    z-index: -1;
    // box-shadow: 0 0 0 2px white, 0 0 0 7px #a47959, 0 0 0 10px black;
    background-image: url(../../resources/images/bg.jpg);
    background-size: 100% 100%;
    background-repeat: no-repeat;
  }
}
.editor-container {
  position: absolute;
  top: 20px;
  left: 20px;
  box-shadow: 0 0 20px 2px gray;

  .board {
    position: relative;
    width: calc(100% - 20px);
    height: calc(100% - 20px);
    top: 10px;
    left: 10px;
    box-shadow: 0 0 0 2px white, 0 0 0 7px #a47959, 0 0 0 10px black;
    background-size: 20% 20%;
    background-repeat: repeat;

    .piece {
      position: absolute;
      top: 0;
      left: 0;
      width: calc(10% - 4px);
      height: calc(10% - 4px);
      transform: translate(2px, 2px);
      background-size: contain;
      background-repeat: no-repeat;
      background-position: center center;
      cursor: pointer;
    }
  }
}
</style>